﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaiwuModFramework.Backend.Comp;
using TaiwuModFramework.Common.Abstract;
using TaiwuModFramework.Common.Base;
using TaiwuModFramework.Common.Utils;

namespace TaiwuModFramework.Common.Manager {
    public class CompManager {

        private static readonly CompManager instance = new CompManager();
        private static readonly Dictionary<Type, string> ids = new Dictionary<Type, string>();
        /// <summary>
        /// 日志组件容器
        /// </summary>
        private static readonly Dictionary<string,LogLevelComp> LogComps = new Dictionary<string,LogLevelComp>();
        private static readonly Drawer<string, BaseTaiwuComp> Comps = new Drawer<string, BaseTaiwuComp>();

        private CompManager() { }

        public static void AddComp(string modIdStr, BaseTaiwuComp comp) {
            if(modIdStr == null || comp == null) return;
            lock(instance) {
                Type type = comp.GetType();
                // 判断是否为已有的日志工具，每个模组只能有一个
                if(typeof(LogLevelComp).Equals(type)) {
                    if(LogComps.ContainsKey(modIdStr)) return;
                    LogComps.Add(modIdStr, (LogLevelComp)comp);
                    Comps.Add(modIdStr, comp);
                    return;
                }
                // 对于其他组件，不可重复加载
                if(ids.TryGetValue(type, out string mid)) {
                    throw new Exception($"组件已被注册到[{mid}],当前模组[{modIdStr}]不可重复注册[{type.AssemblyQualifiedName}]");
                }
                // 添加组件
                Comps.Add(modIdStr, comp);
            }
        }



        public static void AddComp(string modIdStr, IEnumerable<BaseTaiwuComp> list) {
            if(list == null) return;
            foreach(var comp in list) {
                AddComp(modIdStr, comp);
            }
        }



        public static List<BaseTaiwuComp> GetComps(string modIdStr) {
            return new List<BaseTaiwuComp>(Comps.Values(modIdStr));
        }


    }
}
